#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARRAY_SIZE 10
#define FILE_NAME "2022100207+钟杰+实验11.txt"

void generateRandom(int array[], int length) {
    srand(time(0));
    for (int i = 0; i < length; i++) {
        int number = rand();
        array[i] = number;
    }
}

void printArray(int array[], int length) {
    printf("排完序之后的序列为:\n");
    for (int i = 0; i < length; i++)
        printf("%d ", array[i]);
    printf("\n");
}

void selectSort(int* array, int length) {
    int left = 0, right = length - 1;
    while (left <= right) {
        int mini = left;
        for (int i = left + 1; i <= right; ++i) {
            if (array[i] < array[mini])
                mini = i;
        }
        int temp = array[mini];
        array[mini] = array[left];
        array[left] = temp;
        ++left;
    }
}

void writeResultToFile(int* array, int length) {
    FILE* fp = fopen(FILE_NAME, "a");
    if (fp == NULL) {
        perror("open file fail");
        return;
    }
    fprintf(fp, "\n//排完序之后的序列为:\n//");
    for (int i = 0; i < length; i++) 
        fprintf(fp, "%d ", array[i]);
    fprintf(fp, "\n");
    fclose(fp);
}

void copyCodeToFile() {
    FILE* src = fopen(__FILE__, "r");
    FILE* des = fopen(FILE_NAME, "w");
    if (src == NULL || des == NULL) {
        perror("open file fail");
        if (src) fclose(src);
        if (des) fclose(des);
    }
    char buffer[1024];
    fprintf(des, "//源代码:\n");
    while (fgets(buffer, sizeof(buffer), src))
        fputs(buffer, des);
    fclose(des);
    fclose(src);
}

int main() {
    int* array = (int*)malloc(sizeof(int) * ARRAY_SIZE);
    generateRandom(array, ARRAY_SIZE);
    selectSort(array, ARRAY_SIZE);
    printArray(array, ARRAY_SIZE);

    copyCodeToFile();
    writeResultToFile(array, ARRAY_SIZE);
    free(array);    
    return 0;
}